package com.pig.provide.http.context;

import com.pig.common.ClassUtils;
import com.pig.common.JsonUtils;
import com.pig.common.WrapperRpcRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author by 李志伟
 * Create Date: 2019/1/7 16:34
 * Description:
 */
@Slf4j
public class RpcRequestContext {
    private Class clazz;
    private String methodName;
    private List<Class> parameterTypes;
    private List<Object> parameter;

    public Class getClazz() {
        return clazz;
    }

    public Class[] getParameterTypes() {
        Class[] clazz = new Class[parameterTypes.size()];
        return parameterTypes.toArray(clazz);
    }

    public Object[] getParameter() {
        return parameter.toArray();
    }

    public String getMethodName() {
        return methodName;
    }

    public static RpcRequestContext newContext(String methodInfoStr, String argsStr) {
        byte[] methodInfoDecode = Base64.getDecoder().decode(methodInfoStr);
        String jsonStr = new String(methodInfoDecode, StandardCharsets.UTF_8);
        WrapperRpcRequest wrapperRpcRequest = JsonUtils.jsonStrToBean(jsonStr, WrapperRpcRequest.class);
        log.info("request_info = {}", jsonStr);

        //方法参数
        List<Object> parameter = new ArrayList<>();
        //方法参数类型，list中的值为java.util.ArrayList这样的
        List<String> parameterClassName = wrapperRpcRequest.getParameterClassName();
        if (CollectionUtils.isNotEmpty(parameterClassName)) {
            byte[] argsDecode = Base64.getDecoder().decode(argsStr);
            List srcList = JsonUtils.jsonStrToBean(new String(argsDecode, StandardCharsets.UTF_8), ArrayList.class);
            for (int i = 0; i < parameterClassName.size(); i++) {
                String className = parameterClassName.get(i);
                Object o = srcList.get(i);
                Class<?> paraClass = ClassUtils.forName(className);
                Object para = JsonUtils.jsonStrToBean(o.toString(), paraClass);
                parameter.add(para);
            }
        }

        //参数类型
        List<Class> parameterTypes = parameterClassName.stream().map(ClassUtils::forName).collect(Collectors.toList());

        RpcRequestContext context = new RpcRequestContext();
        context.clazz = (ClassUtils.forName(wrapperRpcRequest.getClassName()));
        context.parameterTypes = (parameterTypes);
        context.parameter = (parameter);
        context.methodName = wrapperRpcRequest.getMethodName();
        return context;
    }

}
